package com.coderman.common.starter.idempotent.aspect;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;

import java.util.ArrayList;
import java.util.List;

/**
 * Description:
 * date: 2020/9/24 10:48 上午
 *
 * @author fanchunshuai
 * @version 1.0.0
 * @since JDK 1.8
 */
public class KeyBuilder {
    private static Logger logger = LoggerFactory.getLogger(KeyBuilder.class);
    private static ExpressionParser parser = new SpelExpressionParser();

    /**
     * 获取keyList
     * @param paramValues
     * @param paramNames
     * @param fieldArr
     * @return
     */
    public static List<String> getKeyList(Object[] paramValues, String[] paramNames, String[] fieldArr) {
        List<String> keyList = new ArrayList<>();
        for (int i = 0; i < paramNames.length; i++) {
            for (int j = 0; j < fieldArr.length; j++) {
                if (paramNames[i].equals(fieldArr[j])) {
                    if (paramValues[i] == null) {
                        logger.error("lock value is null ...........");
                        continue;
                    }
                    keyList.add(paramValues[i].toString());
                }
            }
        }

        return keyList;
    }

    /**
     * 从对象中获取keyValue
     *
     * @param key
     * @param object
     * @return
     */
    private static String getKeyValueFromObject(String key, Object object) {
        // 计算SpEL
        try {
            Object argObject = parser.parseExpression(key).getValue(object);
            if (argObject != null) {
                String keyValue = JSON.toJSONString(argObject);
                return keyValue;
            }
        } catch (Exception e) {
            logger.warn("从对象中获取keyValue失败，e={}", e.getMessage());
        }

        return null;
    }

    /**
     * 从对象中获取keyList
     * @param paramValues
     * @param fieldArr
     * @return
     */
    public static List<String> getKeyListFromObject(Object[] paramValues, String[] fieldArr) {
        List<String> keyList = new ArrayList<>();
        for (int i = 0; i < fieldArr.length; i++) {
            for (int j = 0; j < paramValues.length; j++) {
                String value = getKeyValueFromObject(fieldArr[i],paramValues[j]);
                if(StringUtils.isNotEmpty(value)){
                    keyList.add(value);
                }
            }
        }

        return keyList;
    }
}
